package com.lzj.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lzj.mapper.OrdersMapper;
import com.lzj.model.Orders;
import com.lzj.service.OrdersService;
import com.lzj.task.DelayQueueManager;
import com.lzj.task.Task;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.List;

/**
 * @author 李泽伟
 * @description 针对表【orders】的数据库操作Service实现
 * @createDate 2024-02-21 22:53:14
 */
@Service
@Slf4j
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {

    @Resource
    DelayQueueManager delayQueueManager;

    @Scheduled(cron = "0/30 * * * * ?")
    @PostConstruct
    public void changeStatus() {
        log.info("👉开始检测状态");

        LocalDateTime now = LocalDateTime.now().atOffset(ZoneOffset.ofHours(8)).toLocalDateTime();
        List<Orders> list = list(Wrappers.<Orders>lambdaQuery()
                .le(Orders::getStartTime, now.plusMinutes(5))
                .gt(Orders::getStartTime, now.minusMinutes(5))
        );

        for (Orders order : list) {
            if (order.getStatus().equals(0)) {
                // 加入到延时队列
                long expire = order.getStartTime().toInstant(ZoneOffset.ofHours(8)).toEpochMilli()
                        - now.toInstant(ZoneOffset.ofHours(8)).toEpochMilli();
                order.setStatus(1);  // 状态变换
                delayQueueManager.put(new Task<Orders>(order, order.getStartTime()
                        .toInstant(ZoneOffset.ofHours(8))
                        .toEpochMilli())
                );
                log.info("👉{}加入延时队列, expire {} s :", order.getId(), expire / 1000);
            }
        }

    }

}




